package com.jx.lcs.messagepush.web;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.utils.DateUtils;
import com.tianyu.jty.common.web.BaseController;
import com.tianyu.jty.system.utils.UserUtil;
import com.jx.lcs.common.baidu.BaiduPushUtil;
import com.jx.lcs.messagepush.entity.SysMessage;
import com.jx.lcs.messagepush.entity.UserMessage;
import com.jx.lcs.messagepush.service.MessagePushService;
import com.jx.lcs.messagepush.service.UserMessageService;
import com.jx.lcs.thread.ExecutorTask;
import com.jx.lcs.thread.PushMessageThread;
import com.jx.lcs.usersession.entity.UserSession;
import com.jx.lcs.usersession.service.UserSessionService;
import com.jx.lcs.util.common.CharUtil;
import com.jx.lcs.util.common.Constant;

/**
 * 消息推送controller
 * @author ty
 * @date 2015年1月22日
 */
@Controller
@RequestMapping("messagepush")
public class MessagePushController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(MessagePushController.class);
	@Autowired
	private MessagePushService messagePushService;
	@Autowired
	private UserMessageService userMessageService;
	@Autowired
	private UserSessionService userSessionService;
	@Autowired
	private ExecutorTask executorTask;

	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "messagepush/messagePushList";
	}
	
	/**
	 * 获取系统消息列表json
	 */
	@RequestMapping(value="json",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> messagePushList(HttpServletRequest request) {
		
		Page<SysMessage> page=null;
		try {
			page = getPage(request);
			page = messagePushService.findSysMessageList(page, request);
		} catch (Exception e) {
			logger.error("获取系统消息列表出现异常", e);
		}
		return getEasyUIData(page);
	}

	/**
	 * 发送消息跳转
	 * 
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("action", "create");
		return "messagepush/messagePushForm";
	}
	/**
	 * 发送消息
	 * 
	 * @param productType
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(@Valid String msgContent, HttpServletRequest request) {
		try{
			if(StringUtils.isBlank(msgContent)) {
				return "请输入消息内容";
			} else {
				String sendTo = request.getParameter("sendTo");
				List<UserSession> list = null;
				if (sendTo.equals("0")) {//发给所有
					list = userSessionService.findAllUserSession();
				}else {
					String tel = request.getParameter("telephone");
					if (tel.equals("") || tel==null) {
						return "请输入手机号";
					}
					list = userSessionService.findUserSessionByTel(tel);
				}
				if(list != null && list.size() > 0) {
					msgContent = CharUtil.charConvert(msgContent);
					
					//保存系统消息
					SysMessage sysMessage = new SysMessage();
					sysMessage.setTitle(Constant.SYS_MESSAGE_DEFAULT_TITLE);
					sysMessage.setContent(msgContent);
			    	sysMessage.setSendUid(UserUtil.getCurrentUser().getLoginName());
			    	sysMessage.setSendtime(DateUtils.getSysDate());
			    	
			    	messagePushService.save(sysMessage);
			    	
			    	//获取用户未读消息数
			    	Map<String, Integer> msgNumMap = new HashMap<String, Integer>();
			    	List msgNumList = userMessageService.getUnReadMsgCount();
			    	if(msgNumList != null && msgNumList.size() > 0) {
			    		Object[] objArry = null;
			    		for(int i = 0; i < msgNumList.size(); i++) {
			    			objArry = (Object[]) msgNumList.get(i);
			    			msgNumMap.put((String) objArry[0], ((BigInteger) objArry[1]).intValue());
			    		}
			    	}
			    	
			    	//消息推送
			    	HashSet<UserMessage>  userMessageSet = new HashSet<UserMessage>();
			    	String uid = null;
			    	
			    	System.out.println("=========保存消息开始===========");
					for(UserSession session : list) {
						//添加系统消息
						uid = session.getUid();
						
						UserMessage u = new UserMessage();
						u.setMsgId(sysMessage.getId());
						u.setReadStatus("0");
						u.setReadTime(DateUtils.getSysDate());
						u.setUid(uid);
						userMessageSet.add(u);
					}
					//批量保存
					userMessageService.batchSave(userMessageSet);
					
					System.out.println("=========保存消息完成===========");
					
					System.out.println("--推送消息...");
					for(UserSession session : list) {
						//添加系统消息
						uid = session.getUid();
						
						//推送push
						if(session.getBaidu_userId() == null || "".equals(session.getBaidu_userId())) {
							continue;
						} else if(session.getBaidu_channelId() == null || "".equals(session.getBaidu_channelId())) {
							continue;
						} else if(session.getUserInfo() != null && session.getUserInfo().getPushStatus() != null && "false".equals(session.getUserInfo().getPushStatus())) {
							continue;
						}		
						
						Integer msgNum = 0;
						if(msgNumMap.containsKey(uid)) {
							msgNum = msgNumMap.get(uid);
						}
						
						msgNum += 1;
						
						executorTask.doExecute(new PushMessageThread(session, msgContent, msgNum));
					}
				}
			}
			return "success";
			
		} catch(Exception e) {
			logger.error("推送消息到所有用户出现异常", e);
			
			return "发送失败！";
		}
		
	}

}

